; The GIMP -- an image manipulation program
; Copyright (C) 1995 Spencer Kimball and Peter Mattis
; 
; This program is free software; you can redistribute it and/or modify
; it under the terms of the GNU General Public License as published by
; the Free Software Foundation; either version 2 of the License, or
; (at your option) any later version.
; 
; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
; GNU General Public License for more details.
; 
; You should have received a copy of the GNU General Public License
; along with this program; if not, write to the Free Software
; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
;
; Copyright (C) 2007 Kevin Payne paynekj@hotmail.com
;
; Version 1.0 15.03.2007 Changed default settings
; Version 2.0 07.12.2007 Hacked about to work in Gimp 2.4
; Version 3.0 03.05.2008 Added different sharpening modes
; Version 4.0 18.04.2011 Expanded my use of constants
; Version 4.1 20.04.2011 Add version constant
; Version 4.2 20.05.2011 Include the file re-naming code to make this self-contained
; Version 4.3 01.06.2011 Remove the redundant extra re-size
; Version 4.4 30.09.2011 Add in Meet The Gimp Header option
; Version 5.0 19.09.2012 Add in option to do pre-blur, single step scale
; Version 6.0 26.09.2012 Consolidation
; Version 6.1 12.10.2012 Add GimpChat option (760x760)
; Version 6.2 13.11.2012 only maintain one list of targets and get all details from it
; Version 6.3 08.05.2013 Add in flatten option
; Version 6.4 13.10.2014 Add in Half-Size option

(define selffileversion "08.05.2013 Version 6.3")
(define selffilename "\n- kp24_websize.scm")

; constants for the GUIs
(define kpScaleSteps '(3 1 10 1 10 0 1))
(define kpSharpenModes '("Refocus" "Refocus0.6" "Sharpen" "Unsharp" "None"))
(define kp_websize_MyName "Kevin Payne")
(define kp_websize_MyEmail "<paynekj@hotmail.com>")
(define kp_websize_menu_root "<Image>/Script-Fu/Kevin/Sizes")

; Targets MUST have the form "Label (WidthxHeight) name_modifier sharpenMode" and Labels must not contain space characters
(define kp_websize_targets '("Flickr/23 (1024x800) _sml Refocus"  
                             "DPC (800x800) dpc_ Refocus"
                             "GimpChat (760x760) _sml Refocus"
                             "Facebook-Cover (851x315) fb_cover_ Refocus"
                             "Facebook (800x800) fb_ Refocus0.6"
                             "MTG (1000x288) _sml1000 Refocus"
                             "Desktop (2560x1024) _desk Refocus"
                             "Half-Size (w2xh2) _half Refocus"
                            ))

; Insert the string of your choice into the filename
(define (kp_suffix_file_name theImage strSuffix)
  (let* (
         (fnlist (strbreakup (car (gimp-image-get-filename theImage)) DIR-SEPARATOR))         ; break the path into a list
         (fn (car (last fnlist)))                           ; get the file name
         (fnlist (butlast fnlist))                          ; remove the filename
         (fnbase (unbreakupstr (butlast (strbreakup fn ".")) "."))    ; filename without the extension 
         (fnext (car (last (strbreakup fn "."))))                     ; filename extension
         (fnnew (string-append (unbreakupstr fnlist DIR-SEPARATOR) DIR-SEPARATOR fnbase strSuffix "." fnext))
        )
        (gimp-image-set-filename theImage fnnew)
  )
)

; Prefix the file name with the string of your choice
(define (kp_prefix_file_name theImage strPrefix)
  (let* ( 
          (fnlist (strbreakup (car (gimp-image-get-filename theImage)) DIR-SEPARATOR))         ; break the path into a list
          (fn (car (last fnlist)))                  ; get the file name
          (fnlist (butlast fnlist))                    ; remove the filename
          (newfn (string-append (unbreakupstr fnlist DIR-SEPARATOR) DIR-SEPARATOR strPrefix fn)) ; build the new file name
        )
        (gimp-image-set-filename theImage newfn)  ; change the file name
  )
)

; ######################################################################################################
; Procedure to scale the image in steps - seems to make it sharper at the end
; ######################################################################################################
(define (kp_scale_in_steps aimg desired_width desired_height num_of_steps)
  (let* ((owidth (car (gimp-image-width aimg)))
         (oheight (car (gimp-image-height aimg)))
         (width desired_width)
         (height desired_height)
         (width_difference (- owidth desired_width))
         (height_difference (- oheight desired_height))
         (width_step (/ width_difference num_of_steps))
         (height_step (/ height_difference num_of_steps))
         (step_num 1)
        )        
        (if (> num_of_steps 1)
          (while (< step_num num_of_steps) ; loop round progressively shrinking
           (begin
            (set! width (- owidth (* width_step step_num)))
            (set! height (- oheight (* height_step step_num)))
            (gimp-image-scale aimg width height)
 ;           (gimp-message (string-append (number->string width) "x" (number->string height)))
            (set! step_num (+ 1 step_num))
           )
          )
        )
        ; Explicitly do the last re-size to ensure that rounding errors don't come into play
        (set! width desired_width)
        (set! height desired_height)
        (gimp-image-scale aimg width height)
  )
)

; Interactively do sharpening
(define (kp_websize_sharpen aimg adraw sharpmode)
  (let* (
         (sharpModeString (list-ref kpSharpenModes sharpmode))
        )
    (if (string=? sharpModeString "Refocus") (plug-in-refocus RUN-INTERACTIVE aimg adraw 5.0 0.6 0.0 0.5 0.01))
    (if (string=? sharpModeString "Refocus0.6") (plug-in-refocus RUN-NONINTERACTIVE aimg adraw 5.0 0.6 0.0 0.5 0.01))  ; Automatic refocus
    (if (string=? sharpModeString "Sharpen") (plug-in-sharpen RUN-INTERACTIVE aimg adraw 30))
    (if (string=? sharpModeString "Unsharp") (plug-in-unsharp-mask RUN-INTERACTIVE aimg adraw 5.0 0.5 0))
  )       
)

; ######################################################################################################
; Main Code starts here
; ######################################################################################################
(define (script-fu-kp24_websize aimg adraw xsize ysize dominant autodet number_of_steps sharpmode changename namepostfix flatten)
  (let* (
         (dominant 1)
         (owidth 1)
         (oheight 1)
         (width xsize)
         (height ysize)
         (drawable 1)
        )
    (gimp-image-undo-group-start aimg)

    (if (= flatten TRUE)
      (set! drawable (car (gimp-image-flatten aimg)))
      (set! drawable adraw)
    )
    (set! owidth (car (gimp-image-width aimg)))
    (set! oheight (car (gimp-image-height aimg)))
;    (gimp-message "Got Here")

; check if auto detect for size is selected
; if it is, then determine which is bigger, then set the width/height flag appropriately
    (if (= autodet TRUE)
      (begin
        (if (>= oheight owidth)
            (set! dominant 1)
        )
        (if (< oheight owidth)
            (set! dominant 0)
        )
      )
    )
    
    (if (= dominant 0) ; width is the important size, change the height accordingly
        (set! height (/ oheight (/ owidth xsize)))
    )
    (if (= dominant 1) ; height is the important size, change the width accordingly
        (set! width (/ owidth (/ oheight ysize)))
    )

; Scale 
    (kp_scale_in_steps aimg width height number_of_steps)
    
; Sharpen if required
    (kp_websize_sharpen aimg drawable sharpmode)
    
    (if (= changename TRUE)
      (if (= (strcmp (substring namepostfix 0 1) "_") 0)
        (kp_suffix_file_name aimg namepostfix)
        (kp_prefix_file_name aimg namepostfix)
      )
    )
    
    (gimp-selection-none aimg)

    ;Finish the undo group for the process
    (gimp-image-undo-group-end aimg)
    (gimp-displays-flush)
    )
)

;##############################################################################################################

(define (script-fu-kp24_size_configurable aimg adraw xsize ysize dominant autodet number_of_steps sharpmode changename namepostfix flatten)
  (script-fu-kp24_websize aimg adraw xsize ysize dominant autodet number_of_steps sharpmode changename namepostfix flatten)
)

(script-fu-register "script-fu-kp24_size_configurable"
                    "Websize..."
                    (string-append "Shrink an image" selffilename)
                    (string-append kp_websize_MyName kp_websize_MyEmail)
                    kp_websize_MyName
                    selffileversion
                    "RGB* GRAY*"
                    SF-IMAGE "Input Image" 0
                    SF-DRAWABLE "Input Drawable" 0
                    SF-ADJUSTMENT _"Width" '(800 1 3872 1 10 0 1)
                    SF-ADJUSTMENT _"Height" '(800 1 3872 1 10 0 1)
                    SF-OPTION _"Use Width/Height" '(_"Width" _"Height")
                    SF-TOGGLE _"Auto Detect Bigger" TRUE
                    SF-ADJUSTMENT _"Scaling Steps" kpScaleSteps
                    SF-OPTION _"Sharp Type" kpSharpenModes
                    SF-TOGGLE _"Change name?" TRUE
                    SF-STRING _"Name addition" "_sml"
                    SF-TOGGLE _"Flatten?" TRUE
                    )
(script-fu-menu-register "script-fu-kp24_size_configurable" kp_websize_menu_root)

;##############################################################################################################

(define (script-fu-kp24_size_fixed aimg adraw target_index)
  (let* (
          (owidth (car (gimp-image-width aimg)))
          (oheight (car (gimp-image-height aimg)))
          (width owidth) (height oheight) (xsize owidth) (ysize oheight)
          
          (dominent 0)
          (autodet TRUE)
          (number_of_steps 3)
          (sharpmode 0)
          (changename 1)

          ; example target: "Flickr/23 (800x800) _sml"
          (target_list (strbreakup (list-ref kp_websize_targets target_index) " "))
          (width_height_list (strbreakup (substring (cadr target_list) 1 (- (string-length (cadr target_list)) 1) ) "x") )
          
          (width_target (car width_height_list))
          (height_target (cadr width_height_list))
          
          (namepostfix (car (cdr (cdr target_list))))
          
          (flatten TRUE)
          
          (sharpString (car (last target_list)))
          (sharpmode (- (length kpSharpenModes) (length (member sharpString kpSharpenModes))))
        )
;        (error width_height_list)
        (if (equal? width_target "w2")
          (set! xsize (/ owidth 2))
          (set! xsize (string->number (car width_height_list)))
        )
        (if (equal? height_target "h2")
          (set! ysize (/ oheight 2))
          (set! ysize (string->number (cadr width_height_list)))
        )

        (script-fu-kp24_websize aimg adraw xsize ysize dominent autodet number_of_steps sharpmode changename namepostfix flatten)
  )
)

(script-fu-register "script-fu-kp24_size_fixed"
                    _"Fixed Sizes..."
                    (string-append "Shrink an image" selffilename)
                    (string-append kp_websize_MyName kp_websize_MyEmail)
                    kp_websize_MyName
                    selffileversion
                    "RGB* GRAY*"
                    SF-IMAGE "Input Image" 0
                    SF-DRAWABLE "Input Drawable" 0
                    SF-OPTION _"Target" kp_websize_targets
                    )
(script-fu-menu-register "script-fu-kp24_size_fixed" kp_websize_menu_root)

